package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

/**
 * 订单 定时任务处理类
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    OrderMapper orderMapper;



   /* @Scheduled(cron = "0/5 * * * * ?")
    public void test(){
        log.info("定时任务执行了一次");
    }*/

    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder() {
        log.info("开始执行超时未支付定时任务");
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime before = now.minusMinutes(15);
        //查询 前十五分钟超时未支付的订单
        List<Orders> list = orderMapper.selectByStatuAndOrderTime(Orders.PENDING_PAYMENT, before);
        //将所有超时未支付订单 修改为已取消
        if (list != null && list.size() > 0) {
            list.forEach(order -> {
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason(MessageConstant.PENDING_PAYMENT_TIMEOUT);
                order.setCancelTime(LocalDateTime.now());
                orderMapper.update(order);
            });
        }

    }

    @Scheduled(cron = "0 0 4 * * ?")
    public void processDeliverying() {
        log.info("开始执行上一天一直处于派送中的订单");

        //查询上一天 一直处于派送中
        LocalDate now = LocalDate.now();
        LocalDate yesterday = now.plusDays(-1);
        LocalDateTime yesterdayMax = LocalDateTime.of(yesterday, LocalTime.MAX);
        List<Orders> list = orderMapper.selectByStatuAndOrderTime(Orders.DELIVERY_IN_PROGRESS, yesterdayMax);//2021-1-5 23:59:59
//将状态修改为 已完成
        if(list!=null&&list.size()>0){
            list.forEach(order->{
                order.setStatus(Orders.COMPLETED);
                order.setDeliveryTime(yesterdayMax);
                orderMapper.update(order);
            });
        }


    }
}
